package com.ayongw.mobile.greenphone;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * Created by jiangguangtao on 2017/4/23.
 */

public class PhoneActionService extends Service {
    private static final String TAG = "Phone acton Service";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "绑定服务！。。。");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(new PhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
        Log.i(TAG, "创建服务！。。。");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "启动服务");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "销毁服务");
    }

    private static class PhoneStateListener extends android.telephony.PhoneStateListener {
        private String incoming = null;

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            try {
                switch (state) {
                    case TelephonyManager.CALL_STATE_RINGING:
                        this.incoming = incomingNumber;
                        Log.i(TAG, "来电振铃 " + incomingNumber);
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        Log.i(TAG, "正在接听来电" + incomingNumber);
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        Log.i(TAG, "电话被挂断了！");
                        break;
                    default:
                        Log.w(TAG, "未识别的状态：" + state + "  no." + incomingNumber);
                }
            } catch (Exception e) {
                Log.i(TAG, "判断电话事件异常！");
            }
        }
    }
}
